package com.bookstore.servlet;

import com.bookstore.bean.User;
import com.bookstore.services.UserServices;
import com.bookstore.services.impl.UserServicesImpl;
import com.bookstore.utils.WebUtils;
import com.google.code.kaptcha.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

public class UserServlet extends BaseServlet {
    UserServices userServices=new UserServicesImpl();
    //用户登录
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        HttpSession session = request.getSession();
        String code = request.getParameter("code");
        String sessionCode = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if(sessionCode.equals(code)){
            User user = userServices.login(new User(null, username, 1));
            if (user!=null){
                request.getRequestDispatcher("").forward(request,response);
            }else {
                request.setAttribute("userpwd","账户或密码错误！！");
                response.sendRedirect("");
            }
        }else {
            request.setAttribute("codeMsg","验证码错误！！");
            response.sendRedirect("");
        }

    }

    //用户注册
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取到所有的参数封装成集合
        Map<String, String[]> map = request.getParameterMap();
        User user = WebUtils.copyParamToBean(map, new User());
        boolean register = userServices.register(user);
        if (register!=true){
            //注册失败
            request.setAttribute("user",user);//将对象存入以便表单回显
            request.setAttribute("","验证码错误！！");
            response.sendRedirect("");
        }else {
            HttpSession session = request.getSession();
            session.setAttribute("username",user.getUsername());
            request.getRequestDispatcher("").forward(request,response);
        }
    }

    //用户登出
    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        request.getRequestDispatcher("").forward(request,response);
    }
}
